﻿import { Skill, SkillUse, ActiveBuff } from "../core/rpg/types";
import { SkillType, LogType, TargetType, PassiveTriggerType, attackKey, Attribute_base } from "../shared/face/enums";
import SkillManager from "../core/rpg/skill/SkManager";
import BuffManager from "../core/rpg/skill/BuffManager";
import { BattleArea } from "../core/rpg/battleArea";
import type rpg_component from "../component/rpg_component";
import BattleLogger from "../core/rpg/BattleLogger";
import sdk from '../core/index';

import { ModernBaseService } from './base/ModernBaseService';
import { ModernRPGService } from './ModernRPGService';
import { DIContainer } from '../infrastructure/di';

/**
 * RPG服务类 - 兼容性包装器
 * 职责：
 * 1. 为旧代码提供兼容性支持
 * 2. 将调用转发到ModernRPGService
 * 3. 数据格式转换
 * 4. 逐步迁移到新架构
 */
export class RPGService extends ModernBaseService {
    private modernRPGService: ModernRPGService;

    constructor(container?: DIContainer) {
        super(container);
        this.modernRPGService = new ModernRPGService(container);
    }

    /**
     * 服务初始化
     */
    protected async onInit(): Promise<void> {
        await this.modernRPGService.init();
        this.log('RPGService (compatibility wrapper) initialized');
    }

    /**
     * 服务销毁
     */
    protected async onDestroy(): Promise<void> {
        await this.modernRPGService.destroy();
        this.log('RPGService (compatibility wrapper) destroyed');
    }

    /**
     * 学习技能 (兼容性方法)
     * @param currentSkills 当前技能列表 (已废弃，仅为兼容性保留)
     * @param skillData 技能数据
     * @returns 学习结果
     * @deprecated 请使用 modernRPGService.learnSkill 替代
     */
    learnSkill(currentSkills: SkillUse[], skillData: SkillUse): {
        success: boolean;
        message: string;
        newSkills: SkillUse[];
    } {
        // 兼容性实现 - 直接处理数组操作
        const skill = SkillManager.getSkillById(skillData.skillId);
        if (!skill) {
            return {
                success: false,
                message: '技能不存在',
                newSkills: currentSkills
            };
        }

        // 检查是否已经学会此技能
        const existingSkillIndex = currentSkills.findIndex(s => s.skillId === skillData.skillId);
        
        if (existingSkillIndex !== -1) {
            return {
                success: false,
                message: '已经学会此技能',
                newSkills: currentSkills
            };
        }

        // 从技能配置中获取最大等级，如果没有配置则使用默认值
        const maxLevel = (skill as any).maxLevel || 10;

        // 初始化技能数据
        const newSkill: SkillUse = {
            ...skillData,
            level: 1,
            maxLevel: maxLevel, // 使用从配置中读取的最大等级
            permanentBoosts: {},
            useCount: 0
        };

        const newSkills = [...currentSkills, newSkill];
        
        return {
            success: true,
            message: `学会技能: ${skill.name}`,
            newSkills
        };
    }

    /**
     * 学习技能 (现代化方法)
     * @param playerId 玩家ID
     * @param skillData 技能数据
     * @returns 学习结果
     */
    async learnPlayerSkill(playerId: string, skillData: any): Promise<any> {
        try {
            const skillConfig = {
                id: skillData.skillId,
                name: skillData.reName || skillData.skillId,
                description: '',
                type: skillData.type || 'active',
                level: skillData.level || 1,
                maxLevel: skillData.maxLevel || 10,
                data: skillData
            };
            
            return await this.modernRPGService.learnSkill(playerId, skillConfig);
        } catch (error) {
            return this.handleBusinessError(error, 'learnPlayerSkill');
        }
    }

    /**
     * 升级技能（通用方法，支持SkillUse和DataSkill类型）
     * @param currentSkills 当前技能列表（可以是SkillUse[]或DataSkill[]）
     * @param skillId 技能ID
     * @param options 升级选项
     * @returns 升级结果
     */
upgradeSkill(
        currentSkills: any[], 
        skillId: string
    ): {
        success: boolean;
        message: string;
        newSkills?: any[];
        skill?: any;
        leveledUp: boolean;
        newLevel: number;
        beforeLevel: number;
        afterLevel: number;
    } {
        const isEquipSkill = false
        const skillType = 'SkillUse'
        
        const skillIndex = currentSkills.findIndex(s => s.skillId === skillId);
        if (skillIndex === -1) {
            return {
                success: false,
                message: '技能不存在',
                newSkills: currentSkills,
                leveledUp: false,
                newLevel: 0,
                beforeLevel: 0,
                afterLevel: 0
            };
        }

        const skill = currentSkills[skillIndex];
        const beforeLevel = skill.level || 1;
        const maxLevel = skill.maxLevel || 10;

        // 检查是否可以升级
        if (beforeLevel >= maxLevel) {
            return {
                success: false,
                message: '技能已达到最大等级',
                newSkills: currentSkills,
                leveledUp: false,
                newLevel: beforeLevel,
                beforeLevel,
                afterLevel: beforeLevel
            };
        }

        // 直接提升一级
        const afterLevel = beforeLevel + 1;
        const leveledUp = true;

        if (isEquipSkill) {
            // 装备技能升级逻辑
            skill.level = afterLevel;
   
            
            const skillName = skill.reName || skill.skillId;
            return {
                success: true,
                message: `${skillName}升级成功！${beforeLevel}级 -> ${afterLevel}级`,
                skill,
                leveledUp,
                newLevel: afterLevel,
                beforeLevel,
                afterLevel,
                newSkills: currentSkills
            };
        } else {
            // 普通技能升级逻辑（SkillUse类型）
            // 获取技能配置，检查是否有levelUpBoost配置
            const skillConfig = SkillManager.getSkillById(skillId);
        let levelUpMessage = '';
        
        // 所有技能都可以升级，检查是否有额外的升级属性配置
        if (skillConfig && skillConfig.data && skillConfig.data.length > 0) {
            const firstEffect = skillConfig.data[0];
            const permanentBoosts = { ...skill.permanentBoosts };
            
            // 如果有levelUpBoost配置，应用额外的升级属性提升
            if (firstEffect.levelUpBoost) {
                // 处理attRange提升
                if (firstEffect.levelUpBoost.attRange) {
                    const currentAttRangeBoost = permanentBoosts.attRange || 0;
                    permanentBoosts.attRange = currentAttRangeBoost + firstEffect.levelUpBoost.attRange;
                    levelUpMessage += `，攻击倍率永久提升${firstEffect.levelUpBoost.attRange}`;
                }
                
                // 处理其他可能的升级提升
                if (firstEffect.levelUpBoost.damage) {
                    const currentDamageBoost = permanentBoosts.damage || 0;
                    permanentBoosts.damage = currentDamageBoost + firstEffect.levelUpBoost.damage;
                    levelUpMessage += `，伤害永久提升${firstEffect.levelUpBoost.damage}`;
                }
                
                if (firstEffect.levelUpBoost.cooldown) {
                    const currentCooldownBoost = permanentBoosts.cooldown || 0;
                    permanentBoosts.cooldown = currentCooldownBoost + firstEffect.levelUpBoost.cooldown;
                    levelUpMessage += `，冷却时间永久减少${firstEffect.levelUpBoost.cooldown}`;
                }
            }
            
            // 更新技能数据
            const updatedSkill: SkillUse = {
                ...skill,
                level: afterLevel,
                permanentBoosts
            };
            
            const newSkills = [...currentSkills];
            newSkills[skillIndex] = updatedSkill;
            
            const skillName = skillConfig?.name || skillId;
            
            return {
                success: true,
                message: `${skillName}升级到${afterLevel}级！${levelUpMessage}`,
                newSkills,
                leveledUp,
                newLevel: afterLevel,
                beforeLevel,
                afterLevel
            };
        } else {
            // 如果找不到技能配置，不允许升级
            return {
                success: false,
                message: `找不到技能配置，无法升级`,
                newSkills: currentSkills,
                leveledUp: false,
                newLevel: beforeLevel,
                beforeLevel,
                afterLevel: beforeLevel
            };
        }
        }
    }

    /**
     * 使用技能（增加使用次数和可能的永久提升）
     * @param currentSkills 当前技能列表
     * @param skillId 技能ID
     * @param permanentBoostType 永久提升类型（可选）
     * @param boostAmount 提升数值（可选）
     * @returns 使用结果
     */
useSkill(currentSkills: SkillUse[], skillId: string, permanentBoostType?: string, boostAmount?: number): {
        success: boolean;
        message: string;
        newSkills: SkillUse[];
        newUseCount: number;
    } {
        const skillIndex = currentSkills.findIndex(s => s.skillId === skillId);
        if (skillIndex === -1) {
            return {
                success: false,
                message: '技能不存在',
                newSkills: currentSkills,
                newUseCount: 0
            };
        }

        const skill = currentSkills[skillIndex];
        const newUseCount = (skill.useCount || 0) + 1;
        const permanentBoosts = { ...skill.permanentBoosts };

        // 如果有永久提升，记录它
        if (permanentBoostType && boostAmount !== undefined) {
            const currentBoost = permanentBoosts[permanentBoostType] || 0;
            permanentBoosts[permanentBoostType] = currentBoost + boostAmount;
        }

        // 更新技能数据
        const updatedSkill: SkillUse = {
            ...skill,
            useCount: newUseCount,
            permanentBoosts
        };

        const newSkills = [...currentSkills];
        newSkills[skillIndex] = updatedSkill;

        const skillConfig = SkillManager.getSkillById(skillId);
        const skillName = skillConfig?.name || skillId;

        let message = `${skillName}使用次数：${newUseCount}`;
        if (permanentBoostType && boostAmount !== undefined) {
            message += `，${permanentBoostType}永久提升${boostAmount}点`;
        }

        return {
            success: true,
            message,
            newSkills,
            newUseCount
        };
    }

    /**
     * 获取技能的永久提升值
     * @param skill 技能数据
     * @param boostType 提升类型
     * @returns 提升数值
     */
getSkillPermanentBoost(skill: SkillUse, boostType: string): number {
        return skill.permanentBoosts?.[boostType] || 0;
    }

    /**
     * 计算技能实际效果（考虑等级和永久提升）
     * @param skill 技能数据
     * @param baseValue 基础数值
     * @param boostType 提升类型
     * @returns 实际数值
     */
calculateSkillEffect(skill: SkillUse, baseValue: number, boostType?: string): number {
        let finalValue = baseValue;
        
        // 等级加成（每级增加10%）
        const level = skill.level || 1;
        finalValue *= (1 + (level - 1) * 0.1);
        
        // 永久提升加成
        if (boostType) {
            const permanentBoost = this.getSkillPermanentBoost(skill, boostType);
            finalValue += permanentBoost;
        }
        
        return Math.max(0, finalValue);
    }

    /**
     * 获取技能列表
     * @param skillUses 技能使用列表
     * @returns 技能详情列表
     */
getSkillList(skillUses: SkillUse[]): Skill[] {
        const skills: Skill[] = [];
        
        skillUses.forEach(skillUse => {
            const skill = SkillManager.getSkillById(skillUse.skillId);
            if (skill) {
                skills.push({
                    ...skill,
                    name: skillUse.desc || skillUse.reName || skill.name
                });
            }
        });

        return skills;
    }

    /**
     * 计算战力
     * @param attributes 属性对象
     * @param skills 技能列表
     * @param level 等级
     * @returns 战力值
     */
calculatePower(attributes: any, skills: SkillUse[], level: number): number {
        let power = 0;
        
        // 基础属性战力
        power += (attributes[Attribute_base.物理攻击] || 0) * 2;
        power += (attributes[Attribute_base.魔法攻击] || 0) * 2;
        power += (attributes[Attribute_base.物理防御] || 0) * 1.5;
        power += (attributes[Attribute_base.魔法防御] || 0) * 1.5;
        power += (attributes[Attribute_base.最大生命值] || 0) * 0.5;
        // 暂时没有法力值属性，注释掉
        // power += (attributes[Attribute_base.法力值] || 0) * 0.3;
        
        // 技能战力
        skills.forEach(skillUse => {
            const skill = SkillManager.getSkillById(skillUse.skillId);
            if (skill) {
                power += skill.quality * 100;
            }
        });
        
        // 等级战力
        power += level * 50;
        
        return Math.floor(power);
    }

    /**
     * 获取属性详情 (兼容性方法)
     * @param rpgComponent RPG组件
     * @returns 属性详情
     * @deprecated 请使用 modernRPGService.getPlayerAttributes 替代
     */
    getAttributeDetails(rpgComponent: rpg_component): {
        baseAttributes: { [key: string]: number };
        equipAttributes: { [key: string]: number };
        totalAttributes: { [key: string]: number };
    } {
        // 兼容性实现 - 直接从组件获取
        const baseAttributes: { [key: string]: number } = {};
        const equipAttributes: { [key: string]: number } = {};
        const totalAttributes: { [key: string]: number } = {};
        
        const commonAttributes = [
            Attribute_base.物理攻击,
            Attribute_base.魔法攻击,
            Attribute_base.物理防御,
            Attribute_base.魔法防御,
            Attribute_base.最大生命值
            // 暂时没有法力值属性
        ];
        
        commonAttributes.forEach(attr => {
            baseAttributes[attr] = rpgComponent.getAttribute(attr);
            equipAttributes[attr] = 0; // 暂时没有单独的装备属性获取方法
            totalAttributes[attr] = rpgComponent.getAttribute(attr);
        });
        
        return {
            baseAttributes,
            equipAttributes,
            totalAttributes
        };
    }

    /**
     * 获取玩家属性详情 (现代化方法)
     * @param playerId 玩家ID
     * @returns 属性详情
     */
    async getPlayerAttributeDetails(playerId: string): Promise<any> {
        try {
            return await this.modernRPGService.getPlayerAttributes(playerId);
        } catch (error) {
            return this.handleBusinessError(error, 'getPlayerAttributeDetails');
        }
    }

    /**
     * 升级技能 (现代化方法)
     * @param playerId 玩家ID
     * @param skillId 技能ID
     * @returns 升级结果
     */
    async upgradePlayerSkill(playerId: string, skillId: string): Promise<any> {
        try {
            return await this.modernRPGService.upgradeSkill(playerId, skillId);
        } catch (error) {
            return this.handleBusinessError(error, 'upgradePlayerSkill');
        }
    }

    /**
     * 计算玩家战力 (现代化方法)
     * @param playerId 玩家ID
     * @returns 战力值
     */
    async calculatePlayerPower(playerId: string): Promise<number> {
        try {
            return await this.modernRPGService.calculatePlayerPower(playerId);
        } catch (error: any) {
            this.log(`Error calculating power for player ${playerId}: ${error.message}`, 'error');
            return 0;
        }
    }

    /**
     * 添加经验值 (现代化方法)
     * @param playerId 玩家ID
     * @param exp 经验值
     * @param source 经验来源
     * @returns 升级结果
     */
    async addPlayerExperience(playerId: string, exp: number, source: string = 'unknown'): Promise<any> {
        try {
            return await this.modernRPGService.addExperience(playerId, exp, source);
        } catch (error) {
            return this.handleBusinessError(error, 'addPlayerExperience');
        }
    }

    /**
     * 获取玩家技能列表 (现代化方法)
     * @param playerId 玩家ID
     * @returns 技能列表
     */
    async getPlayerSkillList(playerId: string): Promise<any[]> {
        try {
            const skills = await this.modernRPGService.getPlayerSkills(playerId);
            return skills.map(skill => ({
                skillId: skill.id,
                reName: skill.name,
                level: skill.level,
                maxLevel: skill.maxLevel,
                type: skill.type,
                ...skill.data
            }));
        } catch (error: any) {
            this.log(`Error getting skills for player ${playerId}: ${error.message}`, 'error');
            return [];
        }
    }

    /**
     * 获取玩家战斗数据 (现代化方法)
     * @param playerId 玩家ID
     * @returns 战斗数据
     */
    async getPlayerBattleData(playerId: string): Promise<any> {
        try {
            return await this.modernRPGService.getPlayerBattleData(playerId);
        } catch (error) {
            return this.handleBusinessError(error, 'getPlayerBattleData');
        }
    }

    /**
     * 获取现代化服务实例 (供直接访问)
     * @returns ModernRPGService实例
     */
    getModernService(): ModernRPGService {
        return this.modernRPGService;
    }

    /**
     * 获取技能冷却信息
     * @param skills 技能列表
     * @param cooldowns 冷却时间记录
     * @returns 技能冷却信息
     */
getSkillCooldowns(skills: SkillUse[], cooldowns: { [key: string]: number }): {
        skillId: string;
        name: string;
        cooldown: number;
        remainingCooldown: number;
        canUse: boolean;
    }[] {
        const now = Date.now();
        
        return skills.map(skillUse => {
            const skill = SkillManager.getSkillById(skillUse.skillId);
            if (!skill) {
                return {
                    skillId: skillUse.skillId,
                    name: skillUse.reName || 'Unknown',
                    cooldown: 0,
                    remainingCooldown: 0,
                    canUse: false
                };
            }
            
            const lastUsed = cooldowns[skillUse.skillId] || 0;
            const cooldownTime = skill.cooldown * 1000; // 转换为毫秒
            const remainingCooldown = Math.max(0, cooldownTime - (now - lastUsed));
            
            return {
                skillId: skillUse.skillId,
                name: skillUse.desc || skillUse.reName || skill.name,
                cooldown: skill.cooldown,
                remainingCooldown: Math.ceil(remainingCooldown / 1000),
                canUse: remainingCooldown === 0
            };
        });
    }

    /**
     * 检查技能是否可用
     * @param skillId 技能ID
     * @param cooldowns 冷却时间记录
     * @returns 是否可用
     */
canUseSkill(skillId: string, cooldowns: { [key: string]: number }): boolean {
        const skill = SkillManager.getSkillById(skillId);
        if (!skill) return false;
        
        const now = Date.now();
        const lastUsed = cooldowns[skillId] || 0;
        const cooldownTime = skill.cooldown * 1000;
        
        return (now - lastUsed) >= cooldownTime;
    }

    /**
     * 获取战斗状态
     * @param rpgComponent RPG组件
     * @returns 战斗状态
     */
getBattleStatus(rpgComponent: rpg_component): {
        isAlive: boolean;
        currentHp: number;
        maxHp: number;
        hpPercentage: number;
        isInBattle: boolean;
    } {
        const maxHp = rpgComponent.getAttribute(Attribute_base.最大生命值);
        
        return {
            isAlive: rpgComponent.hp_now > 0,
            currentHp: rpgComponent.hp_now,
            maxHp: maxHp,
            hpPercentage: maxHp > 0 ? (rpgComponent.hp_now / maxHp) * 100 : 0,
            isInBattle: false // 暂时没有battleId属性
        };
    }

    /**
     * 处理升级
     * @param currentLevel 当前等级
     * @param currentExp 当前经验
     * @param addedExp 增加的经验
     * @returns 升级结果
     */
processLevelUp(currentLevel: number, currentExp: number, addedExp: number): {
        newLevel: number;
        newExp: number;
        leveledUp: boolean;
        levelsGained: number;
    } {
        let newLevel = currentLevel;
        let newExp = currentExp + addedExp;
        let leveledUp = false;
        let levelsGained = 0;
        
        // 简单的升级公式：每级需要 (level * 100) 经验
        while (newExp >= (newLevel * 100)) {
            newExp -= (newLevel * 100);
            newLevel++;
            leveledUp = true;
            levelsGained++;
        }
        
        return {
            newLevel,
            newExp,
            leveledUp,
            levelsGained
        };
    }

    /**
     * 创建技能展示卡片
     * @param skillId 技能ID
     * @param caster 施法者（可选）
     * @returns 技能卡片
     */
createSkillCard(skillId: string, caster?: any): any {
        const card = sdk.tool.card.create2();
        SkillManager.client_data(skillId, card, caster);
        return card;
    }

    /**
     * 获取Buff状态
     * @param activeBuffs 激活的Buff列表
     * @returns Buff状态信息
     */
getBuffStatus(activeBuffs: ActiveBuff[]): {
        buffCount: number;
        buffs: {
            name: string;
            remainingDuration: number;
            stackCount: number;
            isPositive: boolean;
        }[];
    } {
        return {
            buffCount: activeBuffs.length,
            buffs: activeBuffs.map(buff => ({
                name: buff.buff.name,
                remainingDuration: buff.remainingDuration,
                stackCount: buff.stackCount,
                isPositive: true // 可以根据buff类型判断
            }))
        };
    }

    /**
     * 计算伤害
     * @param attacker 攻击者
     * @param target 目标
     * @param damage 基础伤害
     * @param attackType 攻击类型
     * @returns 最终伤害
     */
calculateDamage(
        attacker: rpg_component,
        target: rpg_component,
        damage: number,
        attackType: attackKey
    ): number {
        // 基础伤害计算
        let finalDamage = damage;
        
        // 根据攻击类型应用防御
        switch (attackType) {
            case attackKey.物理攻击:
                finalDamage = Math.max(1, finalDamage - target.getAttribute(Attribute_base.物理防御));
                break;
            case attackKey.魔法攻击:
                finalDamage = Math.max(1, finalDamage - target.getAttribute(Attribute_base.魔法防御));
                break;
            case attackKey.真实攻击:
                // 真实伤害不减防御
                break;
        }
        
        // 应用随机浮动 (90% - 110%)
        const randomFactor = 0.9 + Math.random() * 0.2;
        finalDamage = Math.floor(finalDamage * randomFactor);
        
        return Math.max(1, finalDamage);
    }

    /**
     * 处理治疗
     * @param healer 治疗者
     * @param target 目标
     * @param healAmount 治疗量
     * @returns 实际治疗量
     */
processHealing(healer: rpg_component, target: rpg_component, healAmount: number): number {
        const maxHp = target.getAttribute(Attribute_base.最大生命值);
        const actualHeal = Math.min(healAmount, maxHp - target.hp_now);
        
        return Math.max(0, actualHeal);
    }
    
    /**
     * 计算经验值变化
     * @param currentExp 当前经验
     * @param maxExp 最大经验
     * @param level 当前等级
     * @param amount 经验变化量
     * @returns 经验计算结果
     */
calculateExpChange(
        currentExp: number,
        maxExp: number,
        level: number,
        amount: number
    ): {
        newExp: number;
        newMaxExp: number;
        newLevel: number;
        levelUpCount: number;
        levelDownCount: number;
    } {
        let newExp = currentExp;
        let newMaxExp = maxExp;
        let newLevel = level;
        let levelUpCount = 0;
        let levelDownCount = 0;
        
        // 处理正数经验（增加）
        if (amount >= 0) {
            newExp += amount;
            
            // 循环处理经验溢出，可能连续升级多次
            while (newExp >= newMaxExp) {
                newExp -= newMaxExp; // 减去本级所需经验
                newLevel++;
                levelUpCount++;
                newMaxExp = Math.round(newMaxExp * 1.2); // 下一级所需经验增加20%
            }
        } 
        // 处理负数经验（扣除）
        else {
            let absAmount = Math.abs(amount); // 取绝对值
            
            // 循环处理经验不足，可能连续降级多次
            while (absAmount > newExp && newLevel > 1) {
                absAmount -= newExp; // 扣除当前等级的经验
                newLevel--;
                levelDownCount++;
                // 计算上一级的经验需求 (反向计算)
                newMaxExp = Math.round(newMaxExp / 1.2);
                newExp = newMaxExp; // 降级后从满经验开始扣除
            }
            
            // 最后扣除剩余经验
            if (newLevel > 1) {
                newExp = Math.max(0, newExp - absAmount);
            } else {
                // 1级时经验最少为0
                newExp = Math.max(0, newExp - absAmount);
            }
        }
        
        return {
            newExp,
            newMaxExp,
            newLevel,
            levelUpCount,
            levelDownCount
        };
    }
    
    /**
     * 计算属性值
     * @param attribute 基础属性数组
     * @param key 属性键
     * @param level 等级
     * @param tempBoosts 临时加成
     * @param equipAttributes 装备属性
     * @param talentAttributes 血统属性
     * @returns 最终属性值
     */
calculateAttribute(
        attribute: { key: Attribute_base, val: number }[],
        key: string,
        level: number,
        tempBoosts: Map<string, Map<string, number>>,
        equipAttributes: number,
        talentAttributes: number
    ): number {
        let baseValue = sdk.tool.common.getCfgAttributeVal(attribute, key);
        baseValue = baseValue * (1 + level * 0.5);
        
        // 考虑 tempBoosts 的影响
        tempBoosts.forEach(buffMap => {
            if (buffMap.has(key)) {
                baseValue += buffMap.get(key)!;
            }
        });
        
        baseValue += equipAttributes;
        baseValue += talentAttributes;
        
        let min = 0;
        if (key == Attribute_base.最大生命值) {
            min = 0.001;
        }
        
        return Math.max(min, baseValue);
    }
    
    /**
     * 计算生命值恢复
     * @param currentHp 当前生命值
     * @param maxHp 最大生命值
     * @param regenRate 恢复速率
     * @param timeDelta 时间间隔（秒）
     * @param isDead 是否死亡
     * @returns 新的生命值
     */
calculateHealthRegeneration(
        currentHp: number,
        maxHp: number,
        regenRate: number,
        timeDelta: number,
        isDead: boolean
    ): number {
        if (isDead || timeDelta <= 1) {
            return currentHp;
        }
        
        const regenAmount = regenRate * timeDelta;
        const newHp = Math.min(currentHp + regenAmount, maxHp);
        
        return newHp;
    }
    
    /**
     * 处理护盾伤害吸收
     * @param shield 当前护盾值
     * @param damage 伤害值
     * @param unitId 单位ID
     * @returns 护盾处理结果
     */
processShieldDamage(
        shield: number,
        damage: number,
        unitId: string
    ): {
        shieldAbsorbed: number;
        remainingShield: number;
        remainingDamage: number;
    } {
        let shieldAbsorbed = 0;
        let remainingShield = shield;
        let remainingDamage = damage;
        
        if (remainingShield > 0) {
            shieldAbsorbed = Math.min(remainingShield, remainingDamage);
            remainingShield -= shieldAbsorbed;
            remainingDamage -= shieldAbsorbed;
            
            // 记录护盾吸收日志
            if (shieldAbsorbed > 0) {
                BattleLogger.log('info', '护盾吸收伤害', {
                    unitId,
                    shieldAbsorbed,
                    remainingShield,
                    remainingDamage
                });
            }
        }
        
        return {
            shieldAbsorbed,
            remainingShield,
            remainingDamage
        };
    }
    
    /**
     * 设置属性值
     * @param attribute 属性数组
     * @param key 属性键
     * @param value 属性值
     * @returns 更新结果
     */
setAttribute(
        attribute: { key: Attribute_base, val: number }[],
        key: Attribute_base,
        value: number
    ): { success: boolean; oldValue: number } {
        let attr = attribute.find(attr => attr.key === key);
        let oldValue = 0;
        
        if (attr) {
            oldValue = attr.val;
            attr.val = value;
        } else {
            attribute.push({ key, val: value });
        }
        
        return { success: true, oldValue };
    }
    
    /**
     * 添加技能到技能列表
     * @param skillList 技能列表
     * @param skill 新技能
     * @param unitId 单位ID
     * @returns 添加结果
     */
addSkillToList(
        skillList: { skillId: string; reName?: string; cooldown: number; desc?: string }[],
        skill: { skillId: string; reName?: string; cooldown?: number; desc?: string },
        unitId: string
    ): {
        success: boolean;
        message: string;
        newSkillList: { skillId: string; reName?: string; cooldown: number; desc?: string }[];
    } {
        try {
            BattleLogger.log('info', '添加技能', {
                skillId: skill.skillId,
                skillName: skill.desc || skill.reName || '未命名',
                unitId
            });
            
            const newSkill = {
                skillId: skill.skillId,
                reName: skill.reName,
                cooldown: skill.cooldown || 0,
                desc: skill.desc
            };
            
            const newSkillList = [...skillList, newSkill];
            
            BattleLogger.log('info', '添加后技能列表', {
                skillList: newSkillList.map(s => s.skillId),
                unitId
            });
            
            return {
                success: true,
                message: '技能添加成功',
                newSkillList
            };
        } catch (error) {
            console.error('添加技能失败:', error);
            return {
                success: false,
                message: '技能添加失败',
                newSkillList: skillList
            };
        }
    }
    
    /**
     * 重新加载技能
     * @param selfSkills 自身技能
     * @param equipSkills 装备技能
     * @returns 合并后的技能列表
     */
reloadSkills(
        selfSkills: { skillId: string; reName?: string; cooldown: number }[],
        equipSkills: { skillId: string; reName?: string; cooldown: number }[]
    ): { skillId: string; reName?: string; cooldown: number }[] {
        return [...selfSkills, ...equipSkills];
    }
    
    /**
     * 减少技能冷却时间
     * @param skills 技能列表
     * @param amount 减少量
     * @returns 更新后的技能列表
     */
reduceCooldowns(
        skills: { skillId: string; reName?: string; cooldown: number }[],
        amount: number = 1
    ): { skillId: string; reName?: string; cooldown: number }[] {
        return skills.map(skill => ({
            ...skill,
            cooldown: Math.max(0, skill.cooldown - amount)
        }));
    }
    
    /**
     * 检查是否死亡
     * @param hp 当前生命值
     * @returns 是否死亡
     */
isDead(hp: number): boolean {
        return hp <= 0;
    }
    
    /**
     * 复活处理
     * @param maxHp 最大生命值
     * @returns 复活后的生命值
     */
revive(maxHp: number): number {
        return maxHp;
    }
    
    /**
     * 创建默认属性
     * @returns 默认属性数组
     */
createDefaultAttributes(): { key: Attribute_base, val: number }[] {
        return [
            { key: Attribute_base.物理攻击, val: 10 },
            { key: Attribute_base.最大生命值, val: 100 }
        ];
    }
    
    /**
     * 初始化战斗状态
     * @returns 初始化后的战斗状态
     */
initializeBattleState(): {
        usedSkills: string[];
        lastUsedSkill: string;
        currentTarget: any;
        activeBuffs: ActiveBuff[];
        tempBoosts: Map<string, Map<string, number>>;
    } {
        return {
            usedSkills: [],
            lastUsedSkill: '',
            currentTarget: null,
            activeBuffs: [],
            tempBoosts: new Map()
        };
    }
    
    /**
     * 分发经验给随从
     * @param exp 总经验
     * @param petCount 随从数量
     * @returns 每个单位获得的经验
     */
distributeExpToPets(exp: number, petCount: number): number {
        const totalUnits = petCount + 1; // 玩家 + 随从
        return exp / totalUnits;
    }

    /**
     * 获取装备可升级的技能列表
     * @param equip 装备对象
     * @returns 可升级的技能列表
     */
    getUpgradeableSkills(equip: any): any[] {
        if (!equip.skill || equip.skill.length === 0) {
            return [];
        }

        return equip.skill.filter((skill: any) => {
            const currentLevel = skill.level || 1;
            const maxLevel = skill.maxLevel || 10;
            return currentLevel < maxLevel;
        });
    }

    /**
     * 获取装备技能升级成功率
     * @param equip 装备对象
     * @param skillId 技能ID
     * @returns 升级成功率（固定100%，因为装备技能升级总是成功）
     */
    getSkillUpgradeSuccessRate(equip: any, skillId: string): number {
        if (!equip.skill || equip.skill.length === 0) {
            return 0;
        }

        const skill = equip.skill.find((s: any) => s.skillId === skillId);
        if (!skill) {
            return 0;
        }

        const currentLevel = skill.level || 1;
        const maxLevel = skill.maxLevel || 10;

        // 如果已达到最大等级，返回0%
        if (currentLevel >= maxLevel) {
            return 0;
        }

        // 装备技能升级总是100%成功
        return 1.0;
    }

    /**
     * 升级装备技能（DataSkill类型）
     * @param equip 装备对象
     * @param skillId 技能ID
     * @returns 升级结果
     */
upgradeEquipSkill(equip: any, skillId: string): {
        success: boolean;
        message: string;
        skill?: any;
        beforeLevel: number;
        afterLevel: number;
    } {
        if (!equip.skill || equip.skill.length === 0) {
            return {
                success: false,
                message: '装备没有技能',
                beforeLevel: 0,
                afterLevel: 0
            };
        }

        const skillIndex = equip.skill.findIndex((s: any) => s.skillId === skillId);
        if (skillIndex === -1) {
            return {
                success: false,
                message: '技能不存在',
                beforeLevel: 0,
                afterLevel: 0
            };
        }

        const skill = equip.skill[skillIndex];
        const beforeLevel = skill.level || 1;
        const maxLevel = skill.maxLevel || 10;

        // 检查是否可以升级
        if (beforeLevel >= maxLevel) {
            return {
                success: false,
                message: '技能已达到最大等级',
                beforeLevel,
                afterLevel: beforeLevel
            };
        }

        // 直接提升一级
        const afterLevel = beforeLevel + 1;
        skill.level = afterLevel;
        equip.updateTime = Date.now();

        const skillName = skill.reName || skill.skillId;

        return {
            success: true,
            message: `${skillName}升级成功！${beforeLevel}级 -> ${afterLevel}级`,
            skill,
            beforeLevel,
            afterLevel
        };
    }
}

// 使用适配器管理实例以保持向后兼容
import { LegacyServiceAdapter } from './base/LegacyServiceAdapter';
export const rpgService = LegacyServiceAdapter.getInstance(RPGService); 
